package personal.dao.accounting;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import personal.domain.accounting.IncomeExpenseCategory;
import personal.domain.accounting.MonthlyCategoryTotal;
import personal.domain.accounting.MonthwiseCalendar;


@Repository
public class IncomeExpenseDAOImpl implements IncomeExpenseDAO {
	@PersistenceContext(unitName="accountingPU")
	private EntityManager em;
	private MonthwiseCalendarDAO monthwiseCalendarDAO;

	public MonthwiseCalendarDAO getMonthwiseCalendarDAO() {
		return monthwiseCalendarDAO;
	}

	@Autowired(required=false)
	public void setMonthwiseCalendarDAO(MonthwiseCalendarDAO monthwiseCalendarDAO) {
		this.monthwiseCalendarDAO = monthwiseCalendarDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<IncomeExpenseCategory> getAllIncomeExpenseCategories() {
		return em.createNamedQuery(IncomeExpenseCategory.INC_EXP_CAT_GET_ALL)
				.getResultList();
	}

	@Override
	public IncomeExpenseCategory saveIncomeExpenseCategory(IncomeExpenseCategory ieCategory) {
		return em.merge(ieCategory);
	}

	@Override
	public void saveMonthlyCategoryTotal(MonthlyCategoryTotal mcTotal) {
		em.merge(mcTotal);
	}

	@Override
	public int adjustMonthlyCategoryTotal(MonthlyCategoryTotal mcTotal) {
		Query query = em.createNamedQuery(MonthlyCategoryTotal.UPDATE_MONTHLY_CAT_TOTAL);
		query.setParameter("categoryId", mcTotal.getIeCategoryId());
		query.setParameter("calendarId", mcTotal.getCalendarId());
		query.setParameter("totalDiff", mcTotal.getTotal());
		return query.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MonthlyCategoryTotal> getMonthlyCategoryTotalsForCalendar(MonthwiseCalendar calendar) {
		List<Long> calendarIds = monthwiseCalendarDAO.getMonthwiseCalendarIds(monthwiseCalendarDAO.getMonthwiseCalendars(calendar));
		Query query = em.createNamedQuery(MonthlyCategoryTotal.GET_MONTHLY_CAT_TOTAL_FOR_CALENDARS);
		query.setParameter("calendarIdList", calendarIds);
		return query.getResultList();
	}
}
